<!-- 产品明细控件 -->
<template>
  <a-space direction="vertical" style="width: 100%">
    <div class="content-item">
      <a-space direction="vertical" style="width: 100%">
        <div class="add-td" style="text-align: right">
          <a-button type="text" @click="addTd" :disabled="props.disabled"
            >添加</a-button
          >
        </div>

        <a-table
          :data="props.props.data"
          :scroll="scroll"
          :pagination="false"
          stripe
          :bordered="{
            headerCell: true,
          }"
        >
          <template #columns>
            <a-table-column title="物料编码" :width="100" align="center"
              ><template #cell="{ record }">
                <a-input disabled v-model="record.number" /></template
            ></a-table-column>
            <a-table-column title="物料名称" :width="100" align="center"
              ><template #cell="{ record }">
                <a-input disabled v-model="record.name" /> </template
            ></a-table-column>
            <a-table-column title="物料规格" :width="100" align="center"
              ><template #cell="{ record }">
                <a-input disabled v-model="record.spec" /></template
            ></a-table-column>
            <a-table-column title="基本单位" :width="100" align="center"
              ><template #cell="{ record }">
                <a-input disabled v-model="record.basicName" /> </template
            ></a-table-column>
            <a-table-column title="销售单价" :width="100" align="center"
              ><template #cell="{ record }">
                <a-input-group>
                  <a-input-number
                    :min="1"
                    ref="refInput"
                    @change="saleMoneyChange(record)"
                    v-model="record.salesPrice"
                    :disabled="props.disabled"
                    hide-button
                  />
                  <a-select
                    default-value="人民币"
                    v-model="record.salesPriceUnit"
                    :disabled="props.disabled"
                    :options="['人民币', '美元', '港币']"
                  />
                </a-input-group> </template
            ></a-table-column>
            <a-table-column title="折扣" :width="100" align="center"
              ><template #cell="{ record }">
                <a-input-number
                  :min="0"
                  @change="cgeDiscount(record)"
                  hide-button
                  v-model="record.discount"
                  :max="100"
                  :disabled="props.disabled"
                >
                  <template #append> % </template>
                </a-input-number>
              </template></a-table-column
            >
            <a-table-column title="销售数量" :width="100" align="center"
              ><template #cell="{ record }">
                <a-input-number
                  :min="1"
                  ref="refInput"
                  @change="amountChange(record)"
                  placeholder="请输入销售数量"
                  v-model="record.amount"
                  :disabled="props.disabled"
                  hide-button /></template
            ></a-table-column>
            <a-table-column title="合计" :width="100" align="center"
              ><template #cell="{ record }">
                <a-input-group>
                  <a-input
                    v-model="record.totalPrice"
                    :disabled="props.disabled"
                  />
                  <a-select
                    default-value="人民币"
                    v-model="record.totalPriceUnit"
                    :disabled="props.disabled"
                    :options="['人民币', '美元', '港币']"
                  />
                </a-input-group>
              </template>
            </a-table-column>
            <a-table-column title="操作" :width="100" align="center"
              ><template #cell="{ rowIndex }">
                <a-space>
                  <a-popconfirm
                    content="确认删除?"
                    type="error"
                    @ok="del(rowIndex)"
                  >
                    <a-button
                      :disabled="props.disabled"
                      type="text"
                      status="danger"
                      >删除</a-button
                    >
                  </a-popconfirm>
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
        <!-- <div>
          <span>总金额：</span><span>{{ copyProps.totalPrice }}</span>
        </div> -->
      </a-space>
    </div>
  </a-space>

  <materielModal
    v-if="materielModalVisible"
    title="物料产品选择"
    categoryName="产品"
    v-model:visible="materielModalVisible"
    @changeVisible="changeVisible"
    @searcchMaterialData="updateMaterialData"
    :isClientHistory="true"
    :clientId="clientId"
  />
</template>

<script lang="ts" setup>
  import { reactive, ref, onMounted, computed, watchEffect } from 'vue';
  import { useRoute } from 'vue-router';
  import mitter from '@/utils/mitt';
  import dayjs from 'dayjs';
  import {
    GetMaterialList,
    PostMaterialList,
  } from '@/api/inventory-management/material-management';
  import materielModal from '@/components/materielModal/index.vue';

  const clientId = ref();
  const materielModalVisible = ref(false);
  const route = useRoute();
  const emit = defineEmits(['update:oneValue', 'update:props']);
  const props = withDefaults(
    defineProps<{
      props: { [propName: string]: any };
      name?: string;
      required?: boolean;
      disabled?: boolean;
      values: any;
      regex?: {
        [name: string]: {
          role: any;
          name: any;
        };
      };
    }>(),
    {}
  );

  interface ParamsType {
    pageIndex: number;
    pageSize: number;
    number: string;
    clientCompanyName: string;
    status: number[];
    startTime: string;
    endTime: string;
  }
  const demandListParams = reactive<ParamsType>({
    pageIndex: 0,
    pageSize: 10,
    number: '',
    clientCompanyName: '',
    status: [],
    startTime: '',
    endTime: '',
  });

  let tableRef = ref();
  const TotalAmount = ref(0);
  const selectedKeys = ref(); // 新增分类弹出框
  let modalVisible = ref(false);
  let currType = ref(''); // 判断是新增主分类还是子分类
  const currForm = reactive({
    list: {},
  });
  const scroll = {
    x: 2000,
  };

  // 选择器配置
  const args = reactive({
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: false,
    },
  });
  const searchName = ref();

  const addTd = () => {
    materielModalVisible.value = true;
  };
  const del = (key: any) => {
    mitter.emit('materialDel', key);
    props.props.data.splice(key, 1);
  };

  // 点击搜索按钮
  const search = () => {
    tableRef.value.loadData();
  };

  // 点击重置按钮
  const reset = () => {
    searchName.value = '';
    tableRef.value.loadData();
  };
  const changeVisible = (e: boolean) => {
    materielModalVisible.value = e;
  };

  // 监听键盘回车，按了回车也会查询
  const keyDown = (e: any) => {
    if (e.keyCode === 13) {
      tableRef.value.loadData();
    }
  };

  // 新增或编辑
  const addOrEdit = (type: string, record?: any) => {
    currType.value = type;
    modalVisible.value = true;
  };

  const amountNum = (record: any) => {
    if (record.salesPrice !== undefined && record.amount !== undefined) {
      record.totalPrice = record.salesPrice * record.amount;
    } else record.totalPrice = 0;
  };

  const cgeDiscount = (record: any) => {
    if (!record.discount) {
      amountNum(record);
    } else {
      amountNum(record);
      let msg = ref(0);
      msg.value = (100 - record.discount) / 100;
      const newMsg = record.salesPrice * record.amount;
      // eslint-disable-next-line operator-assignment
      record.totalPrice = newMsg * msg.value;
    }
  };

  // 修改销售数量
  const amountChange = (record: any) => {
    if (record.salesPrice !== undefined && record.amount !== undefined) {
      cgeDiscount(record);
      // record.totalPrice = record.salesPrice * record.amount;
    } else record.totalPrice = 0;
  };
  // 修改销售单价价格
  const saleMoneyChange = (record: any) => {
    if (record.salesPrice !== undefined && record.amount !== undefined) {
      // record.totalPrice = record.salesPrice * record.amount;
      cgeDiscount(record);
    } else record.totalPrice = 0;
  };

  // 修改销售单价单位
  // const saleUnitChange = (record: any) => {
  //   // 销售单价的单位和合计总价的单位同步
  //   record.salesPriceUnit = record.totalPriceUnit;
  // };
  let refInput = ref();
  // 弹出框确认按钮
  const updateMaterialData = (selectedList: any) => {
    props.props.data = selectedList.map((item: any) => {
      item.managementId = item.id;
      delete item.id;
      return {
        ...item,
      };
    });
    refInput.value?.focus();
    mitter.emit('materialRefresh', props.props.data);
  };

  // 新增分类弹出框
  const add = () => {
    modalVisible.value = true;
  };

  // 新增分类弹出框的自定义事件
  const materialEmit = async (form: any) => {
    try {
      await PostMaterialList(form);
      tableRef.value.loadData();
    } catch (error: unknown) {
      console.log(error);
    }
  };

  const getTotalAmount = (data: any) => {
    let price = 0;
    data.forEach((item: any) => {
      price += item.totalPrice;
    });
    props.props.totalPrice = price;
  };

  watchEffect(() => {
    if (props.props.data) {
      getTotalAmount(props.props.data);
    }
  });

  onMounted(() => {
    if (!props.props.data.length) {
      props.props.data = [];
    }
  });

  mitter.on('clientRefresh', (res) => {
    console.log(99, res);
    clientId.value = res.item.id;
  });
</script>

<style scoped lang="less">
  .content-item {
    background: inherit;
    background-color: rgba(255, 255, 255, 1);
    border: 1px solid rgba(153, 153, 153, 0.349);
    border-radius: 4px;
    -moz-box-shadow: 1px 1px 5px rgba(153, 153, 153, 0.349019607843137);
    -webkit-box-shadow: 1px 1px 5px rgba(153, 153, 153, 0.349019607843137);
    box-shadow: 1px 1px 5px rgba(153, 153, 153, 0.349);
    padding: 20px 20px;
  }
  .container {
    margin-bottom: 20px;

    .content {
      padding: 20px 20px;
    }
    .state-item {
      position: relative;
      left: 50%;
      transform: translateX(-50%);
    }
    .state-item-Y {
      width: 30px;
      height: 30px;
      font-size: 12px;
      border: 1px solid rgba(148, 191, 255, 1);
      background-color: rgba(232, 243, 255, 1);
      border-radius: 5px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #3d7eff;
    }
    .state-item-N {
      color: #f53f3f;
      width: 30px;
      height: 30px;
      font-size: 12px;
      border: 1px solid rgba(251, 172, 163, 1);
      background-color: rgba(255, 236, 232, 1);
      border-radius: 5px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  :deep(.arco-table-tr) {
    height: 40px;
  }
  :deep(.arco-table-th) {
    font-weight: bold;
  }
</style>
